package ds.project.server.presentation;

import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.BorderFactory;
import javax.swing.GroupLayout;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.LayoutStyle;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import javax.swing.border.TitledBorder;
import ds.project.datamodel.CustomException;
import ds.project.server.logic.Server;
import java.awt.FlowLayout;

/**
* This code was edited or generated using CloudGarden's Jigloo
* SWT/Swing GUI Builder, which is free for non-commercial
* use. If Jigloo is being used commercially (ie, by a corporation,
* company or business for any purpose whatever) then you
* should purchase a license for each developer using Jigloo.
* Please visit www.cloudgarden.com for details.
* Use of Jigloo implies acceptance of these licensing terms.
* A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
* THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
* LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
*/
public class ServerGUI extends javax.swing.JFrame{
	private static final long serialVersionUID = 1L;
	private JButton jbtnStartServer;
	private JPanel jpanelPorts;
	private JButton jbtnDirectory;
	private AbstractAction abstractAction1;
	private AbstractAction abstractAction2;
	private JTextField jtxtTCPPort;
	private JLabel jlblTCPPort;
	private Server server;
	private boolean isActive = false;
	private JTextField jtxtDirectory;
	private JPanel jpanelDirectory;
	private JScrollPane jScrollPane1;
	private JTextArea consoleArea;
	private JPanel console;
	private JFileChooser fc = new JFileChooser();

	/**
	* Auto-generated main method to display this JFrame
	*/
	public static void main(String[] args) {
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				ServerGUI inst = new ServerGUI();
				inst.setLocationRelativeTo(null);
				inst.setVisible(true);
			}
		});
	}
	
	public ServerGUI() {
		super();
		initGUI();
	}
	
	private void initGUI() {
		try {
			GroupLayout thisLayout = new GroupLayout((JComponent)getContentPane());
			getContentPane().setLayout(thisLayout);
			setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
			this.setTitle("Servidor concurrente");
			this.setResizable(false);
			{
				jbtnStartServer = new JButton();
				FlowLayout jbtnStartServerLayout = new FlowLayout();
				jbtnStartServer.setLayout(jbtnStartServerLayout);
				jbtnStartServer.setText("Iniciar servidor");
				jbtnStartServer.setSize(186, 21);
				jbtnStartServer.setAction(getAbstractAction1());
			}
			{
				jpanelPorts = new JPanel();
				GroupLayout jpanelPortsLayout = new GroupLayout((JComponent)jpanelPorts);
				jpanelPorts.setLayout(jpanelPortsLayout);
				jpanelPorts.setBorder(BorderFactory.createTitledBorder("Puerto"));
				{
					jlblTCPPort = new JLabel();
					jlblTCPPort.setText("TCP:");
					jlblTCPPort.setSize(-1, 14);
				}
				{
					jtxtTCPPort = new JTextField();
					jtxtTCPPort.setToolTipText("Ingrese el puerto TCP que utilizara el servidor");
					jtxtTCPPort.setText("15480");
				}
				jpanelPortsLayout.setVerticalGroup(jpanelPortsLayout.createSequentialGroup()
					.addGroup(jpanelPortsLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
					    .addComponent(jtxtTCPPort, GroupLayout.Alignment.BASELINE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE)
					    .addComponent(jlblTCPPort, GroupLayout.Alignment.BASELINE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE))
					.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED, 18, GroupLayout.PREFERRED_SIZE));
				jpanelPortsLayout.setHorizontalGroup(jpanelPortsLayout.createSequentialGroup()
					.addContainerGap()
					.addComponent(jlblTCPPort, 0, 35, Short.MAX_VALUE)
					.addGap(7)
					.addComponent(jtxtTCPPort, GroupLayout.PREFERRED_SIZE, 59, GroupLayout.PREFERRED_SIZE)
					.addContainerGap(67, 67));
			}
			thisLayout.setVerticalGroup(thisLayout.createSequentialGroup()
				.addContainerGap()
				.addGroup(thisLayout.createParallelGroup()
				    .addComponent(jpanelPorts, GroupLayout.Alignment.LEADING, GroupLayout.PREFERRED_SIZE, 56, GroupLayout.PREFERRED_SIZE)
				    .addComponent(getJpanelDirectory(), GroupLayout.Alignment.LEADING, GroupLayout.PREFERRED_SIZE, 57, GroupLayout.PREFERRED_SIZE))
				.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
				.addComponent(getConsole(), 0, 211, Short.MAX_VALUE)
				.addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED)
				.addComponent(jbtnStartServer, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE)
				.addContainerGap(17, 17));
			thisLayout.setHorizontalGroup(thisLayout.createSequentialGroup()
				.addContainerGap()
				.addGroup(thisLayout.createParallelGroup()
				    .addGroup(GroupLayout.Alignment.LEADING, thisLayout.createSequentialGroup()
				        .addComponent(jpanelPorts, GroupLayout.PREFERRED_SIZE, 183, GroupLayout.PREFERRED_SIZE)
				        .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
				        .addGroup(thisLayout.createParallelGroup()
				            .addComponent(getJpanelDirectory(), GroupLayout.Alignment.LEADING, 0, 481, Short.MAX_VALUE)
				            .addGroup(GroupLayout.Alignment.LEADING, thisLayout.createSequentialGroup()
				                .addGap(0, 299, Short.MAX_VALUE)
				                .addComponent(jbtnStartServer, GroupLayout.PREFERRED_SIZE, 182, GroupLayout.PREFERRED_SIZE))))
				    .addComponent(getConsole(), GroupLayout.Alignment.LEADING, 0, 670, Short.MAX_VALUE))
				.addGap(8));
			pack();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private AbstractAction getAbstractAction1() {
		if(abstractAction1 == null) {
			abstractAction1 = new AbstractAction("Iniciar servidor", null) {
				private static final long serialVersionUID = 1L;

				public void actionPerformed(ActionEvent evt) {
					
					if (!isActive) {
						if (jtxtTCPPort.getText().isEmpty() || jtxtDirectory.getText().isEmpty()) {
							return;
						}
						try {
							int tcpPort = Integer.parseInt(jtxtTCPPort.getText());
							String directory = jtxtDirectory.getText();
							Logger logger = new Logger(getConsoleArea());
							
							server = new Server(tcpPort, directory, logger);
							server.StartServer();

						} catch (NumberFormatException e) {
							JOptionPane.showMessageDialog(null, e.getMessage(), "Mensaje de error",	JOptionPane.ERROR_MESSAGE);
							return;
						} catch (CustomException e) {
							e.printStackTrace();
							JOptionPane.showMessageDialog(null, e.getMessage()+":"+e.getCause().getMessage(), "Mensaje de error", JOptionPane.ERROR_MESSAGE);
							return;
						}
						jtxtTCPPort.setEnabled(false);
						jtxtDirectory.setEnabled(false);
						jbtnDirectory.setEnabled(false);
						jbtnStartServer.setText("Detener servidor");
						isActive = true;
					}
					else{
						
						try {
							server.StopServer();

						} catch (CustomException e) {
							e.printStackTrace();
							JOptionPane.showMessageDialog(null, e.getMessage(), "Mensaje de error",	JOptionPane.ERROR_MESSAGE);
							System.exit(0);
						}
						
						jtxtTCPPort.setEnabled(true);
						jtxtDirectory.setEnabled(true);
						jbtnDirectory.setEnabled(true);
						jbtnStartServer.setText("Iniciar servidor");
						isActive = false;
					}
					
				}
			};
		}
		return abstractAction1;
	}
	
	private AbstractAction getAbstractAction2() {
		if(abstractAction2 == null) {
			abstractAction2 = new AbstractAction("Seleccionar", null) {
				private static final long serialVersionUID = 1L;
				public void actionPerformed(ActionEvent evt) {					
					fc.setCurrentDirectory(new java.io.File(jtxtDirectory.getText()));
					fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
					if (fc.showOpenDialog(null) == JFileChooser.APPROVE_OPTION){
						jtxtDirectory.setText(fc.getSelectedFile().getAbsolutePath());
						jtxtDirectory.setToolTipText(jtxtDirectory.getText());
					}
				}
			};
		}
		return abstractAction2;
	}
	
	private JPanel getConsole() {
		if(console == null) {
			console = new JPanel();
			GroupLayout consoleLayout = new GroupLayout((JComponent)console);
			console.setLayout(consoleLayout);
			console.setBorder(BorderFactory.createTitledBorder(null, "Consola", TitledBorder.LEADING, TitledBorder.TOP));
			consoleLayout.setHorizontalGroup(consoleLayout.createSequentialGroup()
				.addComponent(getJScrollPane1(), 0, 654, Short.MAX_VALUE));
			consoleLayout.setVerticalGroup(consoleLayout.createSequentialGroup()
				.addComponent(getJScrollPane1(), 0, 185, Short.MAX_VALUE));
		}
		return console;
	}
	
	private JTextArea getConsoleArea() {
		if(consoleArea == null) {
			consoleArea = new JTextArea();
			consoleArea.setEditable(false);
			consoleArea.setAutoscrolls(true);

		}
		return consoleArea;
	}
	
	private JScrollPane getJScrollPane1() {
		if(jScrollPane1 == null) {
			jScrollPane1 = new JScrollPane();
			jScrollPane1.setViewportView(getConsoleArea());
		}
		return jScrollPane1;
	}
	
	private JPanel getJpanelDirectory() {
		if(jpanelDirectory == null) {
			jpanelDirectory = new JPanel();
			GroupLayout jpanelDirectoryLayout = new GroupLayout((JComponent)jpanelDirectory);
			jpanelDirectory.setLayout(jpanelDirectoryLayout);
			jpanelDirectory.setBorder(BorderFactory.createTitledBorder("Directorio"));
			jpanelDirectory.setSize(481, 56);
					jpanelDirectoryLayout.setHorizontalGroup(jpanelDirectoryLayout.createSequentialGroup()
				.addContainerGap()
				.addComponent(getJtxtDirectory(), GroupLayout.PREFERRED_SIZE, 341, GroupLayout.PREFERRED_SIZE)
				.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
				.addComponent(getJbtnDirectory(), GroupLayout.PREFERRED_SIZE, 103, GroupLayout.PREFERRED_SIZE)
				.addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE));
					jpanelDirectoryLayout.setVerticalGroup(jpanelDirectoryLayout.createSequentialGroup()
				.addGroup(jpanelDirectoryLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
				    .addComponent(getJtxtDirectory(), GroupLayout.Alignment.BASELINE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE)
				    .addComponent(getJbtnDirectory(), GroupLayout.Alignment.BASELINE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE))
				.addContainerGap());
		}
		return jpanelDirectory;
	}
	
	private JTextField getJtxtDirectory() {
		if(jtxtDirectory == null) {
			jtxtDirectory = new JTextField();
			jtxtDirectory.setText("C:\\");
		}
		return jtxtDirectory;
	}
	
	private JButton getJbtnDirectory() {
		if(jbtnDirectory == null) {
			jbtnDirectory = new JButton();
			jbtnDirectory.setText("Seleccionar");
			jbtnDirectory.setAction(getAbstractAction2());
		}
		return jbtnDirectory;
	}
}

